// utils/request.js

// const baseUrl = 'https://wxapi.llshs.cn/wxd-api'; // 可以从配置文件读取

function request(path, data = {}, method = 'GET') {
  return new Promise((resolve, resolveWithTokenRefresh) => {
    const app = getApp();
    // 从本地存储中获取 token
    const token = wx.getStorageSync('token');
    const url = `${app.globalData.baseUrl}${path.startsWith('/') ? '' : '/'}${path}`;
    console.log('request url', url, data, method)
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      },
      success: (res) => {
        console.log('request utils result: ', res)
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) { // Token 无效或过期
          refreshTokenAndRetry(path, data, method, resolveWithTokenRefresh);
        } else {
          console.error('Request failed with status:', res.statusCode);
          resolve({ error: 'Request failed', ...res.data });
        }
      },
      fail: (err) => {
        console.error('Network error:', err);
        resolve({ error: 'Network error', ...err });
      }
    });
  });
}

async function refreshTokenAndRetry(url, data, method, resolveWithTokenRefresh) {
  // const app = getApp();
  // const loginUrl = `${app.globalData.baseUrl}/login`;
  // console.log('login url ', loginUrl)
  try {
    const loginRes = await new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject
      });
    });

    if (loginRes.errMsg !== 'login:ok') {
      throw new Error('Failed to get login code');
    }

    const jsCode = loginRes.code;

    // 使用 code 换取新的 token 和 openid
    const loginData = { jsCode };
    const res = await request('login', loginData, 'POST', { 'content-type': 'application/json' });

    console.log('re login result: ', res);

    if (res.code === 200 && res.data.token) {
      // 更新本地存储中的 token 和 openid
      wx.setStorageSync('token', res.data.token);
      wx.setStorageSync('openid', res.data.openid);

      // 重试原始请求
      const retryRes = await request(url, data, method);
      resolveWithTokenRefresh(retryRes);
    } else {
      console.error('Failed to refresh token:', res);
      resolveWithTokenRefresh({ error: 'Failed to refresh token', ...res });
    }
  } catch (err) {
    console.error('Failed to refresh token:', err);
    resolveWithTokenRefresh({ error: 'Failed to refresh token', ...err });
  }

  // wx.login({
  //   success: (res) => {
  //     if (res.errMsg == 'login:ok') {
  //       const jsCode = res.code;
  //       wx.request({
  //         url: loginUrl,
  //         data: { "jsCode": jsCode },
  //         method: 'POST',
  //         header: { 'content-type': 'application/json' },
  //         success: (res) => {
  //           console.log('re login result: ', res)
  //           if (res.statusCode === 200) {

  //             if (res.statusCode === 200 && res.data.data.token) {
  //               // 更新本地存储中的 token
  //               wx.setStorageSync('token', res.data.data.token);
  //               wx.setStorageSync('openid', res.data.data.openid);

  //               // 重试原始请求
  //               try {
  //                 const retryRes = await request(url, data, method);
  //                 resolveWithTokenRefresh(retryRes);
  //               } catch (retryErr) {
  //                 console.error('Retry request failed:', retryErr);
  //                 resolveWithTokenRefresh({ error: 'Retry request failed', ...retryErr });
  //               }
  //             } else {
  //               console.error('Failed to refresh token:', res);
  //               resolveWithTokenRefresh({ error: 'Failed to refresh token', ...res });
  //             }
  //           } else {
  //             console.error('Request failed with status:', res.statusCode);
  //             resolve({ error: 'Request failed', ...res });
  //           }
  //         },
  //         fail: (err) => {
  //           console.error('Failed to refresh token:', err);
  //           resolveWithTokenRefresh({ error: 'Failed to refresh token', ...err });
  //         }
  //       })
  //     }
  //   },
  // })


  // console.log('refreshTokenAndRetry...')
  // // 这里实现无痕登录或刷新 token 的逻辑
  // // 假设我们有一个接口用于刷新 token 或无痕登录
  // const refreshTokenUrl = 'https://wxapi.llshs.cn/wxd-api/refresh-token';

  // wx.request({
  //   url: refreshTokenUrl,
  //   method: 'POST',
  //   data: {
  //     // 可能需要传递旧 token 或其他认证信息
  //     openid: wx.getStorageSync('openid')
  //   },
  //   success: async (res) => {
  //     if (res.statusCode === 200 && res.data.data.token) {
  //       // 更新本地存储中的 token
  //       wx.setStorageSync('token', res.data.data.token);
  //       wx.setStorageSync('openid', res.data.data.openid);

  //       // 重试原始请求
  //       try {
  //         const retryRes = await request(url, data, method);
  //         resolveWithTokenRefresh(retryRes);
  //       } catch (retryErr) {
  //         console.error('Retry request failed:', retryErr);
  //         resolveWithTokenRefresh({ error: 'Retry request failed', ...retryErr });
  //       }
  //     } else {
  //       console.error('Failed to refresh token:', res);
  //       resolveWithTokenRefresh({ error: 'Failed to refresh token', ...res });
  //     }
  //   },
  //   fail: (err) => {
  //     console.error('Failed to refresh token:', err);
  //     resolveWithTokenRefresh({ error: 'Failed to refresh token', ...err });
  //   }
  // });
}

module.exports = request;